var express = require("express");
const { Op } = require("sequelize");
var router = express.Router();

const { Article } = require("../models");
const { NotFoundError, success, failure } = require("../utils/response");

/**
 * 查询文章列表
 * 根据title模糊搜索
 * GET /articles
 */
router.get("/", async function (req, res, next) {
  try {
    // 获取查询参数 title
    const query = req.query;

    // 分页的3个参数 currentPage pageSize offset
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    // 查询条件
    const condition = {
      order: [["id", "ASC"]], // 排序
      limit: pageSize, // 每一页条数
      offset, // 开始位置的索引
    };

    // 如果有查询参数title则添加模糊查询
    if (query.title) {
      condition.where = {
        title: {
          // 查询条件，模糊查询
          [Op.like]: `%${query.title}%`,
        },
      };
    }

    // 通过模型获取数据
    const { count, rows } = await Article.findAndCountAll(condition);

    // 响应数据
    success(res, "查询列表成功", {
      articles: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id查询一个文章
 * GET /articles/:id
 */
router.get("/:id", async (req, res) => {
  try {
    // 根据id查询
    const article = await getArticleById(req);

    success(res, "查询文章成功", { article });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建文章
 * POST /articles
 */
router.post("/", async (req, res) => {
  try {
    // 获取post，body json数据
    // 白名单过滤
    const body = filterBody(req);

    // 创建文章
    const article = await Article.create(body);
    // 返回数据：状态码201
    success(res, "创建文章成功", { article }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id删除一个文章
 * DELETE /articles/:id
 */
router.delete("/:id", async (req, res) => {
  try {
    // 根据id查询
    const article = await getArticleById(req);

    article.destroy();

    success(res, "删除文章成功");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 修改文章
 * PUT /articles/:id
 */
router.put("/:id", async (req, res) => {
  try {
    // 文章是否存在
    const article = await getArticleById(req);

    const body = filterBody(req);

    await article.update(body);

    success(res, "文章修改成功");
  } catch (error) {
    res.status(500).json({
      status: false,
      message: "服务器错误",
      errors: [error.message],
    });
  }
});

async function getArticleById(req) {
  const { id } = req.params;

  const article = await Article.findByPk(id);

  if (!article) throw new NotFoundError(`ID: ${id}的文章没有找到`);

  return article;
}

function filterBody(req) {
  return {
    title: req.body.title,
    content: req.body.content,
  };
}

module.exports = router;
